//
//  ExPeripheralViewController.m
//  OC-Example
//
//  Created by seer on 2018/8/31.
//  Copyright © 2018 apang.men. All rights reserved.
//  官方示例https://developer.apple.com/library/archive/samplecode/BTLE_Transfer/Introduction/Intro.html#//apple_ref/doc/uid/DTS40012927

#import "ExPeripheralViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#define SERVICE_UUID            @"C45D0F4E-A062-4125-BD63-DAF40571FFA0"//服务UUID
#define CHARACTERISTIC_UUID     @"0DB235B2-B575-4BDE-A440-7EC9C46D11EB"//特征UUID
@interface ExPeripheralViewController ()<CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager * peripheralManager;//外围设备
@property (nonatomic, strong) CBMutableCharacteristic * characteristic;//特征
@end

@implementation ExPeripheralViewController

- (instancetype)init {
    return [ExPeripheralViewController loadVFromeMainStoryBoardWith:@"peripheralVC"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.peripheralManager stopAdvertising];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark    CBPeripgeralManager'delegate

-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    //MARK:当前设备的蓝牙状态
    ExLog(@"Peripheral Manager Did Up State 蓝牙状态检测");
    switch (peripheral.state) {
        case CBPeripheralManagerStatePoweredOn:{
            ExLog(@"CBPeripheralManagerStatePoweredOn");//蓝牙开启进行服务配置
            if (!_characteristic) {
                _characteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:SERVICE_UUID] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
                CBUUID * descriptionUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
                CBMutableDescriptor * descriptor = [[CBMutableDescriptor alloc] initWithType:descriptionUUID value:@"呵呵呵"];
                [_characteristic setDescriptors:@[descriptor]];
                CBMutableService * service = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:CHARACTERISTIC_UUID] primary:YES];
                service.characteristics = @[_characteristic];
                [_peripheralManager addService:service];
            }
        }
            break;
        case CBPeripheralManagerStatePoweredOff:
            ExLog(@"CBPeripheralManagerStatePoweredOff");
            break;
        case CBPeripheralManagerStateUnsupported:
            ExLog(@"CBPeripheralManagerStateUnsupported");
            break;
            
        default:
            break;
    }
}

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
    //MARK:订阅事件
    [self sendData];
}

-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
    //MARK:订阅取消
}

- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral {
    //MARK:外围设备准备发送主题
    [self sendData];
}

- (void)sendData {
    //MARK:发送主题
    static BOOL eom = YES;
    if (eom) {
        BOOL isSend = [self.peripheralManager updateValue:[@"EOM" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.characteristic onSubscribedCentrals:nil];
        if (isSend) {
            eom = NO;
            ExLog(@"发送成功");
        }
        return;
    }
    BOOL didSend = [self.peripheralManager updateValue:[[NSString stringWithFormat:@"%u",arc4random()%120] dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.characteristic onSubscribedCentrals:nil];                             
    ExLog(@"发送:-->%@",didSend?@"成功":@"失败");
}
- (IBAction)touchButton:(UIButton *)sender {
    if (sender.selected) {
        [self.peripheralManager stopAdvertising];
    }else{
        [self.peripheralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:SERVICE_UUID]]}];
    }
    sender.selected = !sender.selected;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
